package utils;

import org.apache.commons.lang.StringUtils;
import org.apache.http.*;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.*;
import org.apache.http.entity.StringEntity;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

//import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.Charset;
import java.security.InvalidKeyException;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by zhangxb on 2016/8/26.
 */
public class HttpClientUtils {
    private static final String contentType = "application/json; charset=utf-8";
    private static final String accept = "application/json";

    public static String doGet(String uri, Map<String,Object> param) throws KeyManagementException, NoSuchAlgorithmException, IOException, InvalidKeyException {
        //处理参数和请求地址
        uri = paramToUri(uri,param);
        HttpGet httpGet = new HttpGet(uri);
        //获取httpclient
        HttpClient httpclient = HttpConnectionManager.getHttpClient();

        //设置header信息
//        setHeader(httpGet,contentType,accept);

        //发动请求并处理
        HttpResponse response = httpclient.execute(httpGet);
        int code = response.getStatusLine().getStatusCode();
        HttpEntity entity = response.getEntity();
        String result = EntityUtils.toString(entity, "UTF-8");
        if( code != HttpStatus.SC_OK){
            throw new RuntimeException("访问目标地址失败code:["+code+"]result:["+result+"]");
        }
        return result;
    }
    public static String doPost(String uri, Map<String,Object> param) throws KeyManagementException, NoSuchAlgorithmException, IOException, InvalidKeyException {
        HttpPost httppost = new HttpPost(uri);
        //获取httpclient
        HttpClient httpclient = HttpConnectionManager.getHttpClient();

        //设置请求参数
//        httppost.setEntity(new StringEntity(payload, Charset.forName("UTF-8")));

        //发动请求并处理
        HttpResponse response = httpclient.execute(httppost);
        int code = response.getStatusLine().getStatusCode();
        HttpEntity entity = response.getEntity();
        String result = EntityUtils.toString(entity, "UTF-8");
        if( code != HttpStatus.SC_OK){
            throw new RuntimeException("访问目标地址失败code:["+code+"]result:["+result+"]");
        }
        return result;
    }

    /**get和delete请求时，将参数拼接到uri后面**/
    private static String paramToUri(String uri, Map<String,Object> param) throws IOException {
        //转换为键值对
        if(param != null){
			List<NameValuePair> params = new ArrayList();
		    for (Map.Entry<String,Object> en : param.entrySet()) {
		        String value = en.getValue()==null ? "":en.getValue().toString();
		        if(en.getValue() != null) {
		            params.add(new BasicNameValuePair(en.getKey().toString(), value));
		        }
		    }
		    String str = EntityUtils.toString(new UrlEncodedFormEntity(params, Consts.UTF_8));
		    if(StringUtils.isNotEmpty(str)){
		        uri+="?"+str;
		    }
        }
        return uri;
    }

    /**设置指定header信息*/
    private static void setHeader(HttpRequestBase httpRequestBase, String contentType, String accept) {
        httpRequestBase.addHeader("Content-type",contentType);
        //请求参数以body传输
        httpRequestBase.setHeader("Accept", accept);
    }

}

